#! coding: utf-8
from django.contrib.auth.decorators import login_required
from django.template import RequestContext
from django.shortcuts import render_to_response
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect

from UserManage.views.permission import PermissionVerify
from UserManage.models import User
from website.common.CommonPaginator import SelfPaginator
from models import BlogList
from forms import AddBlogForm, EditBlogForm, BlogGradeForm


def my_render(template, data, request):
    return render_to_response(template, data, context_instance=RequestContext(request))


@login_required
@PermissionVerify()
def BlogListView(request):
    user = User.objects.get(username=request.user)
    if user.id == 1:
        blist = BlogList.objects.all()
    else:
        blist = BlogList.objects.filter(author=user)
    lPage = SelfPaginator(request, blist, 20)
    return my_render('Blog/blog.list.html', locals(), request)


@login_required
@PermissionVerify()
def AddBlog(request):
    author = User.objects.get(username=request.user)
    if request.method == 'POST':
        form = AddBlogForm(request.POST)
        if form.is_valid():
            blog = form.save(commit=False)
            blog.author = author
            form.save()
            return HttpResponseRedirect(reverse('bloglisturl'))
    else:
        form = AddBlogForm()
    return my_render('Blog/blog.add.html', locals(), request)


@login_required
@PermissionVerify()
def BlogEdit(request, ID):
    user = User.objects.get(username=request.user)
    blog = BlogList.objects.get(id=ID)
    if request.method == "POST":
        form = EditBlogForm(request.POST, instance=blog)
        # blog = form.save(commit=False)
        # blog.author = user
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('bloglisturl'))
    else:
        print "form is not valid"
        form = EditBlogForm(instance=blog)
    return my_render('Blog/blog.edit.html', locals(), request)


@login_required
@PermissionVerify()
def BlogDelete(request, ID):
    BlogList.objects.filter(id=ID).delete()
    return HttpResponseRedirect(reverse('bloglisturl'))


@login_required
@PermissionVerify()
def CommentBlog(request, ID):
    user = User.objects.get(username=request.user)
    userid = user.id
    blog = BlogList.objects.get(id=ID)
    if request.method == "POST":
        form = BlogGradeForm(request.POST, instance=blog)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('bloglisturl'))
    else:
        form = BlogGradeForm(instance=blog)
    return my_render('Blog/grade.comment.html', locals(), request)
